var http = require('../../utils/http.js');
const app = getApp()

Page({
  data: {
    checkedGoods: [],
    allChecked: false,
    submitBarText: '结算',
    goods: [],
    totalPrice: 0
  },
  onShow: function() {
    this.getCartData()
  },
  getCartData: function(){
    if(app.globalData.userInfo == null){
      wx.showToast({
        title: "请登录后重新操作",
        icon: "none",
      });
      return
    }
    const userId = wx.getStorageSync('userId')
    var ths = this;
    wx.showLoading();
    //加载购物车列表
    var params = {
      url: "/userApi/cart",
      method: "GET",
      data: {
        current: 1,
        size: 10,
        userId: userId
      },
      callBack: function(res) {
        ths.setData({
          goods: res.data.records
        });
        wx.hideLoading();
      }
    };
    http.request(params);
  },
  onAddNum(event){
    const { goods,checkedGoods } = this.data;
    // 增加数量事件
    const id = Number(event.currentTarget.id)
    const index = event.currentTarget.dataset.index;
    const good = goods[index]
    good.num = event.detail
    goods.splice(index,good)
    // 重新计算总价
    const totalPrice = this.calTotalPrice(goods,checkedGoods)
    this.setData({
      goods,
      totalPrice
    });
    //更新数据库信息
    var params = {
      url: "/userApi/cart",
      method: "PUT",
      data: {
        id: id,
        num: event.detail
      }
    };
    http.request(params);
  },
  onChange(event) {
    // 选中商品
    const { goods } = this.data;
    const checkedGoods = event.detail;
    const totalPrice = this.calTotalPrice(goods,checkedGoods)
    const submitBarText = checkedGoods.length ? `结算`: '结算';
    this.setData({
      checkedGoods,
      totalPrice,
      submitBarText,
    });
  },
  onSubmit() {
    // 结算商品
    wx.showToast({
      title: '点击结算',
      icon: 'none'
    });
  },
  onAllCheckChange(event) {
    // 全部选中事件
    const { goods } = this.data;
    const checkedGoods = []
    if(event.detail){
      // 如果是全部选中
      goods.forEach(g=>{
        checkedGoods.push(g.id.toString());
      })
    }
    const totalPrice = this.calTotalPrice(goods,checkedGoods)
    this.setData({
      allChecked: event.detail,
      checkedGoods,
      totalPrice
    });
  },
  onDelete(event) {
    // 删除商品事件
    const { goods,checkedGoods } = this.data;
    const id = Number(event.currentTarget.id)
    const index = event.currentTarget.dataset.index;
    goods.splice(index,1)
    const totalPrice = this.calTotalPrice(goods,checkedGoods)
    this.setData({
      goods,
      totalPrice
    });
    const userId = wx.getStorageSync('userId')
    var params = {
      url: "/userApi/"+userId+"/cart/"+id,
      method: "delete"
    };
    http.request(params);
  },
  calTotalPrice(goods, checkedGoods) {
    // 计算总价
    const totalPrice = goods.reduce(
      (total, item) =>
        total + (checkedGoods.indexOf(item.id.toString()) !== -1 ? item.price * item.num : 0),
      0,
    );
    return totalPrice;
  }
});